﻿using System.Collections.Generic;
using UnityEngine;

namespace CWM.Skinn
{
	public static partial class SkinnEx
    {
        public static readonly int LatticeDivisonRecommendMax = 64;
        public static readonly int LatticeDivisonMax = 512;

        public static List<Vector3> Lattice3D(this Bounds bounds, int x, int y, int z)
        {
            List<Vector3> lattice = new List<Vector3>();
            bounds.Lattice3D(ref lattice, x, y, z);
            return lattice;
        }

        public static void Lattice3D(this Bounds bounds, ref List<Vector3> lattice, int x, int y, int z)
        {
            x = Mathf.Clamp(x, 1, LatticeDivisonMax);
            y = Mathf.Clamp(z, 1, LatticeDivisonMax);
            z = Mathf.Clamp(z, 1, LatticeDivisonMax);

            BoundsData fb = new BoundsData(bounds);
            bounds.Lattice2D(ref lattice, x, z);
            for (int i = 1; i < y; i++) bounds.Lattice2D(ref lattice, x, z, (PercentagePoint(fb.b2, fb.a1, i, y)).y);
            bounds.Lattice2D(ref lattice, x, y, fb.b2.y);
        }

        public static void Lattice2D(this Bounds bounds, ref List<Vector3> points, int x, int z, float y = 0)
        {
            BoundsData boundsData = bounds;
            x = Mathf.Clamp(x, 1, LatticeDivisonMax);
            z = Mathf.Clamp(z, 1, LatticeDivisonMax);

            Vector3 a1 = boundsData.a1;
            Vector3 a2 = boundsData.a2;
            Vector3 a3 = boundsData.a3;
            Vector3 a4 = boundsData.a4;

            if (y != 0)
            {
                a1.y = y;
                a2.y = y;
                a3.y = y;
                a4.y = y;
            }

            points.Add(a1);
            points.Add(a2);

            for (int ii = 1; ii < z; ii++) points.Add(PercentagePoint(a1, a2, ii, z));

            for (int ii = 0; ii < x; ii++)
            {
                Vector3 xPoint1 = PercentagePoint(a4, a1, ii, x);
                points.Add(xPoint1);
                Vector3 xPoint2 = PercentagePoint(a3, a2, ii, x);
                points.Add(xPoint2);

                for (int iii = 1; iii < z; iii++) points.Add(PercentagePoint(xPoint1, xPoint2, iii, z));
            }
        }

        public static Vector3 GetLatticeSize(this Bounds bounds, int x = 1, int y = 1, int z = 1)
        {
            BoundsData fb = new BoundsData(bounds);
            Vector3 size = Vector3.zero;
            size.x = Vector3.Distance(PercentagePoint(fb.a1, fb.a4, 1, x), fb.a1);
            size.y = Vector3.Distance(PercentagePoint(fb.a1, fb.b3, 1, y), fb.a1);
            size.z = Vector3.Distance(PercentagePoint(fb.a1, fb.a2, 1, z), fb.a1);
            return size;
        }

    }
}